<template>
  <div class="other-expense-container">
    <!-- 顶部信息栏 -->
    <div class="header-section bg-white rounded-lg shadow-md p-6 mb-6">
      <div
        class="flex flex-col md:flex-row items-start md:items-center justify-between gap-6"
      >
        <!-- 左侧：供应商、业务员、日期 -->
        <div class="flex flex-col gap-4">
          <!-- 供应商 -->
          <div class="flex items-center gap-2">
            <label class="required text-gray-700 font-medium">供应商：</label>
            <el-input
              v-model="selectedSupplier.name"
              readonly
              @click="supplierDialogVisible = true"
              class="w-40 cursor-pointer"
            />
          </div>

          <!-- 业务员 -->
          <div class="flex items-center gap-2">
            <label class="text-gray-700 font-medium">业务员：</label>
            <el-select
              v-model="salesman"
              class="w-32"
              @change="handleSalesmanChange"
            >
              <el-option
                v-for="item in salesmanOptions"
                :key="item"
                :label="item"
                :value="item"
              />
              <el-option label="新增职员" value="__new__" />
            </el-select>
          </div>

          <!-- 单据日期 -->
          <div class="flex items-center gap-2">
            <label class="required text-gray-700 font-medium">单据日期：</label>
            <el-date-picker
              v-model="docDate"
              value-format="YYYY-MM-DD"
              class="w-32"
            />
          </div>
        </div>

        <!-- 右侧：附件、单据编号 -->
        <div class="flex flex-col gap-2">
          <el-upload
            action="#"
            :file-list="attachments"
            @preview="handlePreview"
          >
            <el-button
              type="text"
              class="text-blue-600 hover:text-blue-800 flex items-center"
            >
              <el-icon><UploadFilled /></el-icon>
              <span class="ml-1">上传附件</span>
            </el-button>
          </el-upload>
          <span class="text-gray-600">单据编号：{{ docNo }}</span>
        </div>
      </div>
    </div>

    <!-- 支出表格 -->
    <div class="table-section bg-white rounded-lg shadow-md p-6 mb-6">
      <el-table
        :data="tableData"
        border
        stripe
        class="text-sm"
        style="width: 100%; min-width: 1000px"
      >
        <!-- 操作列：添加/删除行 -->
        <el-table-column label="操作" width="180" align="center">
          <template #default="scope">
            <div class="flex items-center justify-center gap-1">
              <el-button
                type="success"
                size="mini"
                @click="addTableRow(scope.$index)"
                class="px-2 py-1"
                >添加</el-button
              >
              <el-button
                type="danger"
                size="mini"
                @click="deleteTableRow(scope.row)"
                class="px-2 py-1"
                >删除</el-button
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column label="支出类别" prop="expenseType" width="120">
          <template #default="scope">
            <el-select v-model="scope.row.expenseType" size="small" required>
              <el-option
                v-for="item in expenseTypeOptions"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="金额" prop="amount" width="100" align="right">
          <template #default="scope">
            <el-input
              v-model.number="scope.row.amount"
              type="number"
              size="small"
              required
              step="0.01"
            />
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remark" width="200" />
        <el-table-column label="源单号" prop="sourceDocNo" width="150" />
        <el-table-column label="源单往来单位" prop="sourceUnit" width="150" />
        <el-table-column label="源单日期" prop="sourceDocDate" width="150">
          <template #default="scope">
            <el-date-picker
              v-model="scope.row.sourceDocDate"
              value-format="YYYY-MM-DD"
              size="small"
            />
          </template>
        </el-table-column>
        <!-- 合计行 -->
        <template #footer>
          <el-table-row class="bg-yellow-100">
            <el-table-cell>合计：</el-table-cell>
            <el-table-cell colspan="5" align="right">
              ¥{{ totalAmount.toFixed(2) }}
            </el-table-cell>
          </el-table-row>
        </template>
      </el-table>
    </div>

    <!-- 底部信息区 -->
    <div class="bottom-section bg-white rounded-lg shadow-md p-6">
      <el-form label-width="80px">
        <el-form-item label="备注信息">
          <el-input
            type="textarea"
            v-model="remark"
            placeholder="暂无备注信息"
            class="h-16"
          />
        </el-form-item>
        <div
          class="flex flex-col md:flex-row items-start md:items-center justify-between gap-6"
        >
          <div class="flex items-center gap-4">
            <el-form-item label="结算账户">
              <el-select v-model="settleAccount" class="w-32">
                <el-option
                  v-for="item in settleAccountOptions"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="付款金额">
              <el-input
                v-model.number="paymentAmount"
                type="number"
                size="small"
                step="0.01"
              />
            </el-form-item>
            <el-form-item label="本次欠款">
              <el-input
                v-model.number="currentArrears"
                type="number"
                size="small"
                readonly
              />
            </el-form-item>
          </div>
          <div class="flex gap-2">
            <el-button type="primary" class="text-sm">保存并新增</el-button>
            <el-button type="success" class="text-sm">保存</el-button>
            <el-button type="info" class="text-sm">审核</el-button>
            <el-button type="text" class="text-sm text-gray-600"
              >历史单据</el-button
            >
            <el-button type="text" class="text-sm text-gray-600"
              >操作日志</el-button
            >
          </div>
        </div>
      </el-form>
    </div>

    <!-- 选择供应商弹窗 -->
    <el-dialog
      title="选择供应商"
      v-model="supplierDialogVisible"
      width="800px"
      class="dialog-custom"
    >
      <el-form :model="supplierQuery" inline label-width="80px" class="mb-4">
        <el-form-item label="类别">
          <el-cascader
            v-model="supplierQuery.categoryPath"
            :options="supplierCategoryOptions"
            :props="{
              expandTrigger: 'hover',
              value: 'value',
              label: 'label',
              children: 'children',
            }"
            size="small"
          />
        </el-form-item>
        <el-form-item label="查询">
          <el-input
            v-model="supplierQuery.keyword"
            placeholder="编号/名称/联系人/电话"
            size="small"
          />
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="supplierQuery.showDisabled" size="small">
            显示禁用供应商
          </el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchSuppliers" size="small">
            查询
          </el-button>
        </el-form-item>
      </el-form>
      <el-table
        :data="supplierList"
        border
        stripe
        @selection-change="handleSupplierSelection"
        class="text-sm"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="类别" prop="category" width="100" />
        <el-table-column label="编号" prop="code" width="120" />
        <el-table-column label="名称" prop="name" width="180" />
        <el-table-column label="联系人" prop="contact" width="100" />
        <el-table-column label="手机" prop="phone" width="120" />
        <el-table-column label="备注" prop="remark" width="150" />
      </el-table>
      <div class="dialog-footer flex justify-between items-center mt-4">
        <el-pagination
          @size-change="(val) => (supplierPageSize = val)"
          @current-change="(val) => (supplierPage = val)"
          :current-page="supplierPage"
          :page-sizes="[10, 50, 100]"
          :page-size="supplierPageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="supplierTotal"
          size="small"
        />
        <div class="flex gap-2">
          <el-button @click="supplierDialogVisible = false" size="small"
            >取消</el-button
          >
          <el-button type="primary" @click="confirmSupplier" size="small"
            >确定</el-button
          >
          <el-button
            type="text"
            size="small"
            class="text-blue-600 hover:text-blue-800"
            @click="addSupplierDialogVisible = true"
            >新增供应商</el-button
          >
        </div>
      </div>
    </el-dialog>

    <!-- 新增供应商弹窗（支持“供应商”和“客户/供应商”双类型） -->
    <el-dialog
      title="新增供应商"
      v-model="addSupplierDialogVisible"
      width="800px"
      class="dialog-custom"
    >
      <el-radio-group v-model="newSupplier.type" class="mb-4">
        <el-radio label="supplier">供应商</el-radio>
        <el-radio label="customer_supplier">客户/供应商</el-radio>
      </el-radio-group>

      <!-- 供应商类型表单 -->
      <template v-if="newSupplier.type === 'supplier'">
        <el-form
          :model="newSupplier.supplierForm"
          label-width="120px"
          class="p-4"
        >
          <el-form-item label="*供应商编号" prop="code">
            <el-input
              v-model="newSupplier.supplierForm.code"
              size="small"
              required
            />
          </el-form-item>
          <el-form-item label="*供应商名称" prop="name">
            <el-input
              v-model="newSupplier.supplierForm.name"
              size="small"
              required
            />
          </el-form-item>
          <el-form-item label="供应商类别" prop="category">
            <el-cascader
              v-model="newSupplier.supplierForm.categoryPath"
              :options="supplierCategoryOptions"
              :props="{
                expandTrigger: 'hover',
                value: 'value',
                label: 'label',
                children: 'children',
              }"
              size="small"
            />
          </el-form-item>
          <el-form-item label="余额日期" prop="balanceDate">
            <el-date-picker
              v-model="newSupplier.supplierForm.balanceDate"
              value-format="YYYY-MM-DD"
              size="small"
            />
          </el-form-item>
          <el-form-item label="期初应付款" prop="initialPayable">
            <el-input
              v-model.number="newSupplier.supplierForm.initialPayable"
              size="small"
              step="0.01"
            />
          </el-form-item>
          <el-form-item label="期初预付款" prop="initialPrepayment">
            <el-input
              v-model.number="newSupplier.supplierForm.initialPrepayment"
              size="small"
              step="0.01"
            />
          </el-form-item>
          <el-form-item label="增值税税率" prop="taxRate">
            <el-input
              v-model.number="newSupplier.supplierForm.taxRate"
              size="small"
              suffix="%"
            />
          </el-form-item>
          <el-form-item label="纳税人识别号" prop="taxNo">
            <el-input v-model="newSupplier.supplierForm.taxNo" size="small" />
          </el-form-item>
          <el-form-item label="开户银行" prop="bank">
            <el-input v-model="newSupplier.supplierForm.bank" size="small" />
          </el-form-item>
          <el-form-item label="银行账号" prop="bankAccount">
            <el-input
              v-model="newSupplier.supplierForm.bankAccount"
              size="small"
            />
          </el-form-item>
          <el-form-item label="交货方式" prop="deliveryMethod">
            <el-select
              v-model="newSupplier.supplierForm.deliveryMethod"
              size="small"
            >
              <el-option
                v-for="item in deliveryMethodOptions"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="是否物流公司" prop="isLogistics">
            <el-select
              v-model="newSupplier.supplierForm.isLogistics"
              size="small"
            >
              <el-option label="是" value="是" />
              <el-option label="否" value="否" />
            </el-select>
          </el-form-item>
          <el-form-item label="业务员" prop="salesman">
            <el-select v-model="newSupplier.supplierForm.salesman" size="small">
              <el-option
                v-for="item in salesmanOptions"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>

          <!-- 联系人表格（动态添加） -->
          <el-form-item label="联系人" prop="contacts">
            <el-table
              :data="newSupplier.supplierForm.contacts"
              border
              stripe
              class="text-sm mb-4"
            >
              <el-table-column label="*联系人" prop="name" width="120">
                <template #default="scope">
                  <el-input v-model="scope.row.name" size="small" required />
                </template>
              </el-table-column>
              <el-table-column label="手机" prop="phone" width="120">
                <template #default="scope">
                  <el-input v-model="scope.row.phone" size="small" />
                </template>
              </el-table-column>
              <el-table-column label="座机" prop="tel" width="120">
                <template #default="scope">
                  <el-input v-model="scope.row.tel" size="small" />
                </template>
              </el-table-column>
              <el-table-column
                label="QQ/微信/Email"
                prop="contactInfo"
                width="180"
              >
                <template #default="scope">
                  <el-input v-model="scope.row.contactInfo" size="small" />
                </template>
              </el-table-column>
              <el-table-column label="联系地址" prop="address" width="180">
                <template #default="scope">
                  <el-input v-model="scope.row.address" size="small" />
                </template>
              </el-table-column>
              <el-table-column label="首要联系人" prop="isPrimary" width="100">
                <template #default="scope">
                  <el-checkbox v-model="scope.row.isPrimary" size="small" />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80" align="center">
                <template #default="scope">
                  <el-button
                    type="danger"
                    size="mini"
                    @click="deleteContact(scope.$index, 'supplier')"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
            <el-button
              type="primary"
              size="mini"
              @click="addContact('supplier')"
              class="mb-2"
              >添加联系人</el-button
            >
          </el-form-item>
        </el-form>
      </template>

      <!-- 客户/供应商类型表单 -->
      <template v-else>
        <el-form
          :model="newSupplier.customerSupplierForm"
          label-width="120px"
          class="p-4"
        >
          <el-form-item label="*编号" prop="code">
            <el-input
              v-model="newSupplier.customerSupplierForm.code"
              size="small"
              required
            />
          </el-form-item>
          <el-form-item label="*名称" prop="name">
            <el-input
              v-model="newSupplier.customerSupplierForm.name"
              size="small"
              required
            />
          </el-form-item>
          <el-form-item label="客户类别" prop="customerCategory">
            <el-cascader
              v-model="newSupplier.customerSupplierForm.customerCategoryPath"
              :options="customerCategoryOptions"
              :props="{
                expandTrigger: 'hover',
                value: 'value',
                label: 'label',
                children: 'children',
              }"
              size="small"
            />
          </el-form-item>
          <el-form-item label="供应商类别" prop="supplierCategory">
            <el-cascader
              v-model="newSupplier.customerSupplierForm.supplierCategoryPath"
              :options="supplierCategoryOptions"
              :props="{
                expandTrigger: 'hover',
                value: 'value',
                label: 'label',
                children: 'children',
              }"
              size="small"
            />
          </el-form-item>
          <el-form-item label="客户等级" prop="customerLevel">
            <el-select
              v-model="newSupplier.customerSupplierForm.customerLevel"
              size="small"
            >
              <el-option
                v-for="item in customerLevelOptions"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="余额日期" prop="balanceDate">
            <el-date-picker
              v-model="newSupplier.customerSupplierForm.balanceDate"
              value-format="YYYY-MM-DD"
              size="small"
            />
          </el-form-item>
          <el-form-item label="期初应收款" prop="initialReceivable">
            <el-input
              v-model.number="
                newSupplier.customerSupplierForm.initialReceivable
              "
              size="small"
              step="0.01"
            />
          </el-form-item>
          <el-form-item label="期初预收款" prop="initialPrepayment">
            <el-input
              v-model.number="
                newSupplier.customerSupplierForm.initialPrepayment
              "
              size="small"
              step="0.01"
            />
          </el-form-item>
          <el-form-item label="增值税税率" prop="taxRate">
            <el-input
              v-model.number="newSupplier.customerSupplierForm.taxRate"
              size="small"
              suffix="%"
            />
          </el-form-item>
          <el-form-item label="交货方式" prop="deliveryMethod">
            <el-select
              v-model="newSupplier.customerSupplierForm.deliveryMethod"
              size="small"
            >
              <el-option
                v-for="item in deliveryMethodOptions"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="关联线路" prop="relatedRoute">
            <el-input
              v-model="newSupplier.customerSupplierForm.relatedRoute"
              size="small"
            />
          </el-form-item>
          <el-form-item label="是否物流公司" prop="isLogistics">
            <el-select
              v-model="newSupplier.customerSupplierForm.isLogistics"
              size="small"
            >
              <el-option label="是" value="是" />
              <el-option label="否" value="否" />
            </el-select>
          </el-form-item>
          <el-form-item label="收款条件" prop="paymentTerms">
            <el-input
              v-model="newSupplier.customerSupplierForm.paymentTerms"
              size="small"
            />
          </el-form-item>
          <el-form-item label="发票信息">
            <div class="grid grid-cols-2 gap-4">
              <el-form-item label="开票公司名" prop="invoiceCompany">
                <el-input
                  v-model="newSupplier.customerSupplierForm.invoiceCompany"
                  size="small"
                />
              </el-form-item>
              <el-form-item label="纳税人识别号" prop="taxNo">
                <el-input
                  v-model="newSupplier.customerSupplierForm.taxNo"
                  size="small"
                />
              </el-form-item>
              <el-form-item label="开户银行" prop="bank">
                <el-input
                  v-model="newSupplier.customerSupplierForm.bank"
                  size="small"
                />
              </el-form-item>
              <el-form-item label="银行账号" prop="bankAccount">
                <el-input
                  v-model="newSupplier.customerSupplierForm.bankAccount"
                  size="small"
                />
              </el-form-item>
              <el-form-item label="开票地址" prop="invoiceAddress">
                <el-input
                  v-model="newSupplier.customerSupplierForm.invoiceAddress"
                  size="small"
                />
              </el-form-item>
              <el-form-item label="开票电话" prop="invoicePhone">
                <el-input
                  v-model="newSupplier.customerSupplierForm.invoicePhone"
                  size="small"
                />
              </el-form-item>
            </div>
          </el-form-item>
          <el-form-item label="业务员" prop="salesman">
            <el-select
              v-model="newSupplier.customerSupplierForm.salesman"
              size="small"
            >
              <el-option
                v-for="item in salesmanOptions"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </template>

      <template #footer>
        <div class="flex justify-end gap-2">
          <el-button @click="addSupplierDialogVisible = false" size="small"
            >关闭</el-button
          >
          <el-button type="primary" @click="saveNewSupplier" size="small"
            >保存</el-button
          >
        </div>
      </template>
    </el-dialog>

    <!-- 新增职员弹窗（复用之前逻辑） -->
    <el-dialog
      title="新增职员"
      v-model="newStaffDialogVisible"
      width="500px"
      class="dialog-custom"
    >
      <el-form :model="newStaff" label-width="100px" class="p-4">
        <el-form-item label="*职员编号" prop="code">
          <el-input v-model="newStaff.code" size="small" required />
        </el-form-item>
        <el-form-item label="*职员名称" prop="name">
          <el-input v-model="newStaff.name" size="small" required />
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="newStaff.phone" size="small" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="flex justify-end gap-2">
          <el-button @click="newStaffDialogVisible = false" size="small"
            >关闭</el-button
          >
          <el-button type="primary" @click="saveNewStaff" size="small"
            >保存</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import {
  ElDialog,
  ElTable,
  ElTableColumn,
  ElForm,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElDatePicker,
  ElButton,
  ElUpload,
  ElMessage,
  ElIcon,
  ElCascader,
  ElRadioGroup,
  ElRadio,
  ElPagination,
} from "element-plus";
import { UploadFilled } from "@element-plus/icons-vue";

// 防抖函数（解决 ResizeObserver 问题）
const debounce = (fn, delay = 100) => {
  let timer = null;
  return (...args) => {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => fn(...args), delay);
  };
};

// 供应商数据
const selectedSupplier = ref({ name: "" });
const supplierDialogVisible = ref(false);
const supplierQuery = reactive({
  categoryPath: [],
  keyword: "",
  showDisabled: false,
});
const supplierCategoryOptions = ref([
  {
    label: "广东",
    value: "guangdong",
    children: [
      {
        label: "海鲜供应商",
        value: "seafood",
        children: [{ label: "测试", value: "test" }],
      },
      { label: "酒水饮料供应商", value: "drinks" },
      { label: "食品供应商", value: "food" },
    ],
  },
  {
    label: "湖南",
    value: "hunan",
    children: [
      { label: "辣条供应商", value: "snack" },
      { label: "零食供应商", value: "snacks" },
    ],
  },
]);
const supplierList = ref([
  {
    category: "广东",
    code: "G00001",
    name: "商品综合批发有限公司",
    contact: "王",
    phone: "180****0000",
    remark: "",
  },
  {
    category: "酒水饮料供应商",
    code: "G00002",
    name: "金小蝶食品贸易有限公司",
    contact: "管先生",
    phone: "188****7777",
    remark: "",
  },
  {
    category: "食品供应商",
    code: "G00003",
    name: "广州食品批发有限公司",
    contact: "小裴",
    phone: "180****4844",
    remark: "",
  },
  {
    category: "食品供应商",
    code: "G00004",
    name: "深圳食品加工有限公司",
    contact: "樊樊",
    phone: "180****5555",
    remark: "",
  },
  {
    category: "广东",
    code: "G00005",
    name: "食品零售供应商",
    contact: "李先生",
    phone: "183****2312",
    remark: "",
  },
  {
    category: "零食供应商",
    code: "G00006",
    name: "零食供应商",
    contact: "",
    phone: "",
    remark: "",
  },
  {
    category: "",
    code: "G00007",
    name: "测试供应商",
    contact: "",
    phone: "",
    remark: "",
  },
  {
    category: "",
    code: "G00008",
    name: "测试",
    contact: "",
    phone: "",
    remark: "",
  },
  {
    category: "",
    code: "G00009",
    name: "测试111",
    contact: "测试",
    phone: "",
    remark: "",
  },
]);
const supplierTotal = ref(15);
const supplierPage = ref(1);
const supplierPageSize = ref(10);
const addSupplierDialogVisible = ref(false);
const newSupplier = reactive({
  type: "supplier", // 默认类型：供应商
  supplierForm: {
    code: "G00010",
    name: "",
    categoryPath: [],
    balanceDate: "2022-01-01",
    initialPayable: 0,
    initialPrepayment: 0,
    taxRate: 0,
    taxNo: "",
    bank: "",
    bankAccount: "",
    deliveryMethod: "",
    isLogistics: "否",
    salesman: "(空)",
    contacts: [
      {
        name: "",
        phone: "",
        tel: "",
        contactInfo: "",
        address: "",
        isPrimary: false,
      },
    ],
  },
  customerSupplierForm: {
    code: "G00011",
    name: "",
    customerCategoryPath: [],
    supplierCategoryPath: [],
    customerLevel: "零售客户",
    balanceDate: "2022-01-01",
    initialReceivable: 0,
    initialPrepayment: 0,
    taxRate: 0,
    deliveryMethod: "",
    relatedRoute: "",
    isLogistics: "否",
    paymentTerms: "",
    invoiceCompany: "",
    taxNo: "",
    bank: "",
    bankAccount: "",
    invoiceAddress: "",
    invoicePhone: "",
    salesman: "(空)",
  },
});

// 业务员数据
const salesmanOptions = ref([
  "(空)",
  "老板",
  "财务-玲",
  "采购-小陈",
  "采购-小王",
  "销售-小李",
]);
const salesman = ref("(空)");
const newStaff = reactive({
  code: "",
  name: "",
  phone: "",
});
const newStaffDialogVisible = ref(false);

// 单据信息
const docDate = ref("2025-06-25");
const docNo = ref("QTZC20250625001");
const attachments = ref([]);
const remark = ref("");

// 表格数据
const expenseTypeOptions = ref(["采购支出", "费用支出", "其他"]);
const tableData = ref([
  {
    id: 1,
    expenseType: "",
    amount: 0,
    remark: "",
    sourceDocNo: "",
    sourceUnit: "",
    sourceDocDate: "",
  },
]);
const totalAmount = computed(() =>
  tableData.value.reduce((sum, item) => sum + item.amount, 0)
);

// 结算信息
const settleAccountOptions = ref(["1002 银行存款", "1001 库存现金"]);
const settleAccount = ref("1002 银行存款");
const paymentAmount = ref(0);
const currentArrears = computed(() => totalAmount.value - paymentAmount.value);

// 其他下拉选项
const customerCategoryOptions = ref([
  {
    label: "广东省内",
    value: "guangdong",
    children: [
      {
        label: "华北地区",
        value: "north",
        children: [
          { label: "零售", value: "retail" },
          { label: "批发", value: "wholesale" },
        ],
      },
      {
        label: "华东地区",
        value: "east",
        children: [{ label: "批发", value: "wholesale" }],
      },
      { label: "华南地区", value: "south" },
      { label: "华中地区", value: "central" },
    ],
  },
]);
const customerLevelOptions = ref([
  "零售客户",
  "批发客户",
  "VIP客户",
  "折扣等级一",
  "折扣等级二",
]);
const deliveryMethodOptions = ref([
  "(空)",
  "快递物流",
  "自配送",
  "自提",
  "其他",
]);

// 供应商方法
const fetchSuppliers = () => console.log("查询供应商参数：", supplierQuery);
const handleSupplierSelection = (val) =>
  (selectedSupplier.value = val[0] || {});
const confirmSupplier = () => (supplierDialogVisible.value = false);
const addContact = (type) => {
  if (type === "supplier") {
    newSupplier.supplierForm.contacts.push({
      name: "",
      phone: "",
      tel: "",
      contactInfo: "",
      address: "",
      isPrimary: false,
    });
  }
};
const deleteContact = (index, type) => {
  if (type === "supplier") {
    newSupplier.supplierForm.contacts.splice(index, 1);
  }
};
const saveNewSupplier = () => {
  if (newSupplier.type === "supplier") {
    const form = newSupplier.supplierForm;
    if (!form.code || !form.name) {
      ElMessage.warning("编号和名称为必填项！");
      return;
    }
    // 模拟添加到供应商列表
    supplierList.value.push({
      category: form.categoryPath.length
        ? supplierCategoryOptions.value.find(
            (item) => item.value === form.categoryPath[0]
          ).label
        : "",
      code: form.code,
      name: form.name,
      contact: form.contacts.find((c) => c.isPrimary)?.name || "",
      phone: form.contacts.find((c) => c.isPrimary)?.phone || "",
      remark: "",
    });
  } else {
    // 客户/供应商逻辑可扩展
  }
  ElMessage.success("供应商添加成功！");
  addSupplierDialogVisible.value = false;
};

// 业务员方法
const handleSalesmanChange = (val) => {
  if (val === "__new__") {
    newStaffDialogVisible.value = true;
    salesman.value = "(空)";
  }
};
const saveNewStaff = () => {
  if (!newStaff.code || !newStaff.name) {
    ElMessage.warning("职员编号、名称为必填项！");
    return;
  }
  salesmanOptions.value.push(newStaff.name);
  ElMessage.success("职员添加成功！");
  newStaffDialogVisible.value = false;
};

// 表格方法（防抖优化）
const updateTable = debounce((newData) => {
  // 检查数据是否真的有变化
  if (JSON.stringify(tableData.value) !== JSON.stringify(newData)) {
    tableData.value = newData;
  }
});
const addTableRow = (index) => {
  const newRow = {
    id: tableData.value.length + 1,
    expenseType: "",
    amount: 0,
    remark: "",
    sourceDocNo: "",
    sourceUnit: "",
    sourceDocDate: "",
  };
  const newData = [...tableData.value];
  newData.splice(index + 1, 0, newRow);
  updateTable(newData);
};
const deleteTableRow = (row) => {
  const newData = tableData.value.filter((item) => item.id !== row.id);
  updateTable(newData);
};

// 附件预览
const handlePreview = (file) => ElMessage.info(`预览附件：${file.name}`);

onMounted(() => fetchSuppliers());
</script>

<style scoped>
.other-expense-container {
  padding: 32px;
  background: #f9fafb;
}
.header-section,
.table-section,
.bottom-section {
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border-radius: 12px;
}
.required::after {
  content: "*";
  color: #f56c6c;
  margin-right: 4px;
}
.el-table {
  --el-table-header-text-color: #303133;
  --el-table-header-background-color: #f5f7fa;
  --el-table-row-hover-background-color: #f0f2f5;
}
.el-table__cell {
  white-space: nowrap;
  overflow: visible;
  text-overflow: clip;
}
.overflow-x-auto {
  overflow-x: auto;
}
::-webkit-scrollbar {
  height: 6px;
  width: 6px;
}
::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}
::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}
::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
@media (max-width: 1024px) {
  .other-expense-container {
    padding: 16px;
  }
  .header-section .flex {
    flex-direction: column;
    gap: 4px;
  }
  .header-section .flex > div {
    min-width: 100%;
  }
}
</style>